<template>
  <nav class="site-navbar" :class="'site-navbar--' + navbarLayoutType">
    <div class="site-navbar__header">
      <h1 class="site-navbar__brand" @click="$router.push({ name: 'home' })">
        <a class="site-navbar__brand-lg" href="javascript:;">外卖平台</a>
        <a class="site-navbar__brand-mini" href="javascript:;">外卖</a>
      </h1>
    </div>
    <div class="site-navbar__body clearfix">
      <el-menu class="site-navbar__menu" mode="horizontal">
        <el-menu-item
          class="site-navbar__switch"
          index="0"
          @click="sidebarFold = !sidebarFold"
        >
          <icon-svg name="zhedie"></icon-svg>
        </el-menu-item>
      </el-menu>
      <el-menu
        class="site-navbar__menu site-navbar__menu--right"
        mode="horizontal"
      >
        <!-- <el-menu-item index="1" @click="$router.push({ name: 'theme' })">
          <template slot="title">
            <el-badge value="new">
              <icon-svg name="shezhi" class="el-icon-setting"></icon-svg>
            </el-badge>
          </template>
        </el-menu-item> -->

        <!-- 设置图标 -->
         <el-menu-item index="1" @click="$router.push({ name: 'sys-config' })">
          <template slot="title">
            <el-badge value="">
              <icon-svg name="shezhi" class="el-icon-setting"></icon-svg>
            </el-badge>
          </template>
        </el-menu-item>

        <!-- 消息 弹窗 -->
        <el-popover
          ref="notificationPopover"
          placement="top-start"
          title="消息"
          width="600"
          trigger="click"
        >
          <div style="text-align: left; margin: 0">
            <!-- 消息内容 -->
            <div v-for="(item, index) in notificationList" :key="item.id">
              <el-card
                shadow="hover"
                class="notificationWrapper"
                v-if="index < 10"
              >
                <!-- 最多显示10个 -->
                <div @click="markReadedAndGoRoute(item)">
                  <span class="notificationContent">{{
                    getTimeShow(item.createTime)
                  }}</span>
                  <span class="notificationContent">{{ item.content }}</span>
                </div>
              </el-card>
            </div>

            <div v-if="notificationList.length <= 0">
              <el-card
                shadow="hover"
                class="notificationWrapper"
              >
                <!-- 最多显示5个 -->
                暂无未读消息
              </el-card>
            </div>

            <el-button
              class="markAllReaded"
              type="primary"
              size="mini"
              plain
              icon="el-icon-delete"
              @click="markAllReaded"
              >标记所有为已读</el-button
            >
            <el-button
              class="markAllReaded"
              type="primary"
              size="mini"
              plain
              icon="el-icon-more-outline"
              @click="goToNotification"
              >查看所有通知</el-button
            >
          </div>
        </el-popover>

        <!-- 消息通知 铃铛 -->
        <el-menu-item v-popover:notificationPopover index="2">
          <template slot="title">
            <el-badge :value="lastestNotificationCount">
              <i class="el-icon-bell"></i>
              <!-- <icon-svg name="shezhi" class="el-icon-bell"></icon-svg> -->
            </el-badge>
          </template>
        </el-menu-item>

        <el-menu-item class="site-navbar__avatar" index="3">
          <el-dropdown :show-timeout="0" placement="bottom">
            <span class="el-dropdown-link">
              <img src="~@/assets/img/avatar.jpg" :alt="userName" />{{
                userName
              }}
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="updatePasswordHandle()"
                >修改密码</el-dropdown-item
              >
              <el-dropdown-item @click.native="logoutHandle()"
                >退出</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </el-menu-item>
      </el-menu>
    </div>
    <!-- 弹窗, 修改密码 -->
    <update-password
      v-if="updatePassowrdVisible"
      ref="updatePassowrd"
    ></update-password>

    <!-- 音频 -->
    <audio
      ref="audio"
      src="http://cdn.350800.xyz/audio/newOrder.mp3"
      muted="muted"
    ></audio>
  </nav>
</template>

<script>
import { goToNotificationByType, emitProxy } from '@/utils/notificationRoute'
import UpdatePassword from './main-navbar-update-password'
import { clearLoginInfo } from '@/utils'
export default {
  data () {
    return {
      notificationList: [],
      lastestNotificationCount: 0,
      updatePassowrdVisible: false
    }
  },
  components: {
    UpdatePassword
  },
  computed: {
    navbarLayoutType: {
      get () {
        return this.$store.state.common.navbarLayoutType
      }
    },
    sidebarFold: {
      get () {
        return this.$store.state.common.sidebarFold
      },
      set (val) {
        this.$store.commit('common/updateSidebarFold', val)
      }
    },
    mainTabs: {
      get () {
        return this.$store.state.common.mainTabs
      },
      set (val) {
        this.$store.commit('common/updateMainTabs', val)
      }
    },
    userName: {
      get () {
        return this.$store.state.user.name
      }
    }
  },
  mounted () {
    this.pullLastestSysNotifications()
    // 手动打开sockeIO链接
    this.$socket.open()

    var that = this
    emitProxy.$on('pullLastestSysNotifications', function (msg) {
      console.log('收到刷新消息')
      that.pullLastestSysNotifications()
    })
  },
  methods: {
    // 跳转到通知页面
    goToNotification () {
      this.goRoute('/#/sys-sysnotification')
    },
    goToNotificationRoute (sysnotification) {
      goToNotificationByType(sysnotification.type, sysnotification.params)
    },
    // 标记单个为已读,并跳转到 消息页面
    markReadedAndGoRoute (sysnotification) {
      this.$http({
        url: this.$http.adornUrl(
          `/sys/sysnotification/info/${sysnotification.id}`
        ),
        method: 'get'
      })
        .then(({ data }) => {
          // 重新拉取未读
          this.pullLastestSysNotifications()
        })
        .catch((e) => {
          this.$message.error('网络错误')
          console.error('网络错误', e)
        })

      this.goToNotificationRoute(sysnotification)
    },
    // 标记所有通知为已读
    markAllReaded () {
      this.$http({
        url: this.$http.adornUrl('/sys/sysnotification/all/allread'),
        method: 'put'
      })
        .then(({ data }) => {
          console.log('标记所有通知为已读 响应', data)
          if (data && data.code === 0) {
            this.$message.success('操作成功')
          } else {
            this.$message.error(data.msg)
          }
        })
        .catch((e) => {
          this.$message.error('网络错误')
          console.error('网络错误', e)
        })
        .then(() => {
          this.pullLastestSysNotifications()
        })
    },
    // 修改密码
    updatePasswordHandle () {
      this.updatePassowrdVisible = true
      this.$nextTick(() => {
        this.$refs.updatePassowrd.init()
      })
    },
    // 退出
    logoutHandle () {
      this.$confirm(`确定进行[退出]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl('/sys/logout'),
            method: 'post',
            data: this.$http.adornData()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              clearLoginInfo()
              this.$router.push({ name: 'login' })
            }
          })
        })
        .catch(() => {})
    },
    // 播放音频
    playAudio () {
      try {
        this.$refs.audio.muted = false
        this.$refs.audio.play()
      } catch (e) {
        this.$messages.error('由于浏览器限制，声音提醒无法使用')
        console.error(e)
      }
    },
    // 登录socketIO
    socketIOLogin () {
      console.log('登录socketIO，uerid', this.$store.state.user.id)
      // this.$socket.emit('STREAM_STATUS', { subscribe: true })// 在页面加载时发起订阅，“STREAM_STATUS”是你跟后端约定好的主题名
      this.$socket.emit('login', this.$store.state.user.id)

      console.log('this.sockets', this.sockets)
      console.log('this.$socket', this.$socket)
      console.log('this.$vueSocketIo', this.$vueSocketIo)

      // this.sockets.join('room' + this.userId, function () {
      //   console.log(this.sockets.rooms)
      // })
    },
    // 查询 所有 最新的 未读 消息
    pullLastestSysNotifications () {
      this.$http({
        url: this.$http.adornUrl('/sys/sysnotification/all/mine/unread'),
        method: 'get'
      }).then(({ data }) => {
        console.log('最新消息', data)
        if (data && data.code === 0) {
          // 消息数量
          this.lastestNotificationCount = data.data.length
          this.notificationList = data.data
        }
      })
    }
  },
  // 通过vue实例对象sockets实现组件中的事件监听
  sockets: {
    connected (data) {
      console.log('connected', data)
    },
    // 售后状态变化
    afterSaleStatusChange (data) {},
    orderStatusChange (data) {
      console.log('socketio通知', data)
      emitProxy.$emit('pullLastestSysNotifications')
    },
    newPayedOrder (data) {
      console.log('newPayedOrder', data)
      if (data == '1') {
        this.playAudio()
      }
    },
    STREAM_STATUS (data) {
      // 后端按主题名推送的消息数据
      console.log('Page：' + data)
    },
    myBroadcast (data) {
      console.log('myBroadcast', data)
    },
    connect: function () {
      this.socketIOLogin()

      // socket的connect事件
      console.log('socket connected from Page')
    },
    disconnect: function () {
      console.log(' disconnected from Page')
    },
    reconnect: function () {
      this.socketIOLogin()
    }
  }
}
</script>

<style scoped>
.el-menu.el-menu--horizontal {
  border-bottom: none !important;
}
.el-menu--horizontal > .el-menu-item.is-active {
  border-bottom: white !important;
}
.markAllReaded {
  margin-bottom: 0%;
  width: 48%;
  clear: both;
}
.notificationContent {
  padding: 5px 10px;
  margin-top: 10px;
  height: 30px;
  line-height: 30px;
  font-size: 20px inherit;
  text-overflow: ellipsis;
}

.notificationWrapper {
  cursor: pointer;
}

.el-card >>> .el-card__body {
  padding: 10px !important;
}
</style>